"""
任务管理页面
"""
import json
import webbrowser
from datetime import datetime
from PyQt6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QPushButton,
                           QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox,
                           QLineEdit, QLabel, QFileDialog, QMessageBox, QScrollArea,
                           QFrame, QComboBox, QDialog, QMenu, QSpinBox, QDoubleSpinBox, QTextEdit)
from PyQt6.QtCore import Qt, QSize, pyqtSignal, QTimer
from PyQt6.QtGui import QIcon, QAction, QColor, QCursor
from com.db.task_manager import TaskManager
from com.db.models import Task
from com.db.scan_record_price_analysis_manager import ScanRecordPriceAnalysisManager
from gui.styles.table_style import apply_default_table_style, set_columns_stretch
from gui.styles.pagination_style import PaginationWidget
from com.constants.wear_ranges import WearCategory, WEAR_CATEGORY_NAMES
from .price_analysis_history_dialog import PriceAnalysisHistoryDialog
from .profit_rate_price_history_dialog import ProfitRatePriceHistoryDialog
from .task_batch_edit_dialog import TaskBatchEditDialog
from gui.widgets.investment_report_dialog import InvestmentReportDialog
import logging

logger = logging.getLogger(__name__)

class ClickableLabel(QLabel):
    """可点击的标签"""
    def __init__(self, text, parent=None):
        super().__init__(parent)
        # 将换行符转换为HTML的<br>标签
        html_text = text.replace('\n', '<br>')
        self.setText(html_text)
        self.setTextFormat(Qt.TextFormat.RichText)
        self.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction)
        self.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        self.setWordWrap(True)  # 启用自动换行
        
        # 设置样式
        self.setStyleSheet("""
            QLabel {
                color: #1890ff;
                text-decoration: none;
                background: transparent;
                padding: 2px;
            }
            QLabel:hover {
                color: #40a9ff;
            }
        """)

class TaskPage(QWidget):
    """任务管理页面"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.task_manager = TaskManager()
        self.scan_record_price_analysis_manager = ScanRecordPriceAnalysisManager()
        self.row_checkboxes = []  # 初始化复选框列表
        self.current_sort_column = -1  # 当前排序列
        self.current_sort_order = Qt.SortOrder.AscendingOrder  # 当前排序顺序
        self.setup_ui()
        self.init_tags()  # 初始化标签
        self.load_data()  # 加载数据
        
        # 添加日志记录器
        global logger
        logger = logging.getLogger(__name__)
        logger.setLevel(logging.INFO)
        if not logger.handlers:
            handler = logging.StreamHandler()
            handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
            logger.addHandler(handler)
    
    def setup_ui(self):
        """初始化UI"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(20)
        
        # 顶部操作区域
        top_layout = QHBoxLayout()
        
        # 搜索框
        search_layout = QHBoxLayout()
        
        # 商品ID输入框
        id_label = QLabel("商品ID：")
        id_label.setStyleSheet("font-size: 14px;")
        self.id_input = QLineEdit()
        self.id_input.setPlaceholderText("输入商品ID...")
        self.id_input.setMinimumWidth(120)
        self.id_input.setStyleSheet("""
            QLineEdit {
                padding: 5px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                font-size: 14px;
            }
            QLineEdit:focus {
                border-color: #40a9ff;
            }
        """)
        self.id_input.returnPressed.connect(self.on_search)
        
        # 商品名称输入框
        name_label = QLabel("商品名称：")
        name_label.setStyleSheet("font-size: 14px;")
        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText("输入商品名称...")
        self.search_input.setMinimumWidth(200)
        self.search_input.setStyleSheet("""
            QLineEdit {
                padding: 5px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                font-size: 14px;
            }
            QLineEdit:focus {
                border-color: #40a9ff;
            }
        """)
        self.search_input.returnPressed.connect(self.on_search)
        
        search_layout.addWidget(id_label)
        search_layout.addWidget(self.id_input)
        search_layout.addSpacing(10)
        search_layout.addWidget(name_label)
        search_layout.addWidget(self.search_input)
        
        # 最小在售数量输入框
        min_sell_num_label = QLabel("最小在售数量：")
        min_sell_num_label.setStyleSheet("font-size: 14px;")
        self.min_sell_num_input = QLineEdit()
        self.min_sell_num_input.setPlaceholderText("输入最小在售数量...")
        self.min_sell_num_input.setMinimumWidth(120)
        self.min_sell_num_input.setStyleSheet("""
            QLineEdit {
                padding: 5px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                font-size: 14px;
            }
            QLineEdit:focus {
                border-color: #40a9ff;
            }
        """)
        self.min_sell_num_input.returnPressed.connect(self.on_search)
        
        search_layout.addSpacing(10)
        search_layout.addWidget(min_sell_num_label)
        search_layout.addWidget(self.min_sell_num_input)
        
        # 建议捡漏价范围
        price_label = QLabel("建议捡漏价：")
        price_label.setStyleSheet("font-size: 14px;")
        
        self.min_price_input = QLineEdit()
        self.min_price_input.setPlaceholderText("最小值")
        self.min_price_input.setMinimumWidth(80)
        self.min_price_input.setStyleSheet("""
            QLineEdit {
                padding: 5px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                font-size: 14px;
            }
            QLineEdit:focus {
                border-color: #40a9ff;
            }
        """)
        self.min_price_input.returnPressed.connect(self.on_search)
        
        price_separator = QLabel("-")
        price_separator.setStyleSheet("font-size: 14px;")
        
        self.max_price_input = QLineEdit()
        self.max_price_input.setPlaceholderText("最大值")
        self.max_price_input.setMinimumWidth(80)
        self.max_price_input.setStyleSheet("""
            QLineEdit {
                padding: 5px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                font-size: 14px;
            }
            QLineEdit:focus {
                border-color: #40a9ff;
            }
        """)
        self.max_price_input.returnPressed.connect(self.on_search)
        
        search_layout.addSpacing(10)
        search_layout.addWidget(price_label)
        search_layout.addWidget(self.min_price_input)
        search_layout.addWidget(price_separator)
        search_layout.addWidget(self.max_price_input)
        
        # 搜索按钮
        self.search_btn = QPushButton("查询")
        self.search_btn.setStyleSheet("""
            QPushButton {
                background-color: #1890ff;
                border: none;
                border-radius: 4px;
                color: white;
                padding: 5px 15px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #40a9ff;
            }
            QPushButton:pressed {
                background-color: #096dd9;
            }
        """)
        self.search_btn.clicked.connect(self.on_search)
        
        # 重置按钮
        self.reset_btn = QPushButton("重置")
        self.reset_btn.setStyleSheet("""
            QPushButton {
                background-color: #ffffff;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                color: #595959;
                padding: 5px 15px;
                font-size: 14px;
                margin-left: 5px;
            }
            QPushButton:hover {
                border-color: #40a9ff;
                color: #40a9ff;
            }
            QPushButton:pressed {
                border-color: #096dd9;
                color: #096dd9;
            }
        """)
        self.reset_btn.clicked.connect(self.on_reset)
        
        search_layout.addWidget(self.search_btn)
        search_layout.addWidget(self.reset_btn)
        
        # 添加到顶部布局
        top_layout.addLayout(search_layout)
        
        # 标签筛选行
        tags_row_layout = QHBoxLayout()
        
        # 状态筛选下拉框
        status_label = QLabel("状态：")
        status_label.setStyleSheet("font-size: 14px;")
        self.status_combo = QComboBox()
        self.status_combo.setMinimumWidth(100)
        self.status_combo.setStyleSheet("""
            QComboBox {
                padding: 5px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                font-size: 14px;
            }
            QComboBox:focus {
                border-color: #40a9ff;
            }
            QComboBox::drop-down {
                border: none;
                width: 20px;
            }
            QComboBox::down-arrow {
                image: url(down_arrow.png);
                width: 12px;
                height: 12px;
            }
        """)
        self.status_combo.addItem("全部", -1)
        self.status_combo.addItem("启用", 1)
        self.status_combo.addItem("停用", 0)
        self.status_combo.currentIndexChanged.connect(self.on_search)
        
        # 外观筛选下拉框
        wear_label = QLabel("外观：")
        wear_label.setStyleSheet("font-size: 14px;")
        self.wear_combo = QComboBox()
        self.wear_combo.setMinimumWidth(120)
        self.wear_combo.setStyleSheet("""
            QComboBox {
                padding: 5px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                font-size: 14px;
            }
            QComboBox:focus {
                border-color: #40a9ff;
            }
            QComboBox::drop-down {
                border: none;
                width: 20px;
            }
            QComboBox::down-arrow {
                image: url(down_arrow.png);
                width: 12px;
                height: 12px;
            }
        """)
        # 添加外观选项
        self.wear_combo.addItem("全部", None)
        for category in WearCategory:
            self.wear_combo.addItem(WEAR_CATEGORY_NAMES[category], category.value)
        self.wear_combo.currentIndexChanged.connect(self.on_search)
        
        tags_row_layout.addWidget(status_label)
        tags_row_layout.addWidget(self.status_combo)
        tags_row_layout.addWidget(wear_label)
        tags_row_layout.addWidget(self.wear_combo)
        tags_row_layout.addSpacing(20)  # 添加间距
        
        # 标签筛选
        tags_label = QLabel("标签筛选：")
        tags_label.setStyleSheet("""
            QLabel {
                font-size: 14px;
                padding: 5px 0;
            }
        """)
        tags_row_layout.addWidget(tags_label)
        
        # 标签滚动区域
        self.tags_scroll = QScrollArea()
        self.tags_scroll.setWidgetResizable(True)
        self.tags_scroll.setStyleSheet("""
            QScrollArea {
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                background: white;
            }
        """)
        self.tags_scroll.setMinimumHeight(60)
        self.tags_scroll.setMaximumHeight(60)
        
        # 标签容器
        self.tags_container = QWidget()
        self.tags_layout = QHBoxLayout(self.tags_container)
        self.tags_layout.setContentsMargins(5, 5, 5, 5)
        self.tags_layout.setSpacing(10)
        self.tags_layout.setAlignment(Qt.AlignmentFlag.AlignLeft)
        
        self.tags_scroll.setWidget(self.tags_container)
        self.tag_checkboxes = {}  # 存储标签复选框
        
        # 将标签滚动区域添加到标签行布局，并设置拉伸因子
        tags_row_layout.addWidget(self.tags_scroll, 1)  # 添加拉伸因子1，使标签区域占据剩余空间
        
        # 将标签行布局添加到主布局
        layout.addLayout(top_layout)
        layout.addLayout(tags_row_layout)
        
        # 添加任务按钮
        self.add_task_btn = QPushButton("添加任务")
        self.add_task_btn.setStyleSheet("""
            QPushButton {
                background-color: #52c41a;
                border: none;
                border-radius: 4px;
                color: white;
                padding: 5px 15px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #73d13d;
            }
            QPushButton:pressed {
                background-color: #389e0d;
            }
        """)
        self.add_task_btn.clicked.connect(self.on_add_task)
        
        # 批量编辑按钮
        self.batch_edit_btn = QPushButton("批量编辑")
        self.batch_edit_btn.setStyleSheet("""
            QPushButton {
                background-color: #1890ff;
                border: none;
                border-radius: 4px;
                color: white;
                padding: 5px 15px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #40a9ff;
            }
            QPushButton:pressed {
                background-color: #096dd9;
            }
        """)
        self.batch_edit_btn.clicked.connect(self.on_batch_edit)
        
        # 批量删除按钮
        self.batch_delete_btn = QPushButton("批量删除")
        self.batch_delete_btn.setStyleSheet("""
            QPushButton {
                background-color: #ff4d4f;
                border: none;
                border-radius: 4px;
                color: white;
                padding: 5px 15px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #ff7875;
            }
            QPushButton:pressed {
                background-color: #d9363e;
            }
        """)
        self.batch_delete_btn.clicked.connect(self.on_batch_delete)
        
        # 导入按钮
        self.import_btn = QPushButton("导入")
        self.import_btn.setStyleSheet("""
            QPushButton {
                background-color: #1890ff;
                border: none;
                border-radius: 4px;
                color: white;
                padding: 5px 15px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #40a9ff;
            }
            QPushButton:pressed {
                background-color: #096dd9;
            }
        """)
        self.import_btn.clicked.connect(self.on_import)
        
        top_layout.addStretch()
        top_layout.addWidget(self.add_task_btn)
        top_layout.addWidget(self.batch_edit_btn)
        top_layout.addWidget(self.batch_delete_btn)
        top_layout.addWidget(self.import_btn)
        
        # 表格
        self.table = QTableWidget()
        self.table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)  # 禁用编辑功能
        self.table.cellDoubleClicked.connect(self.on_row_double_clicked)  # 连接双击事件
        self.table.cellClicked.connect(self.on_cell_clicked)  # 连接单元格点击事件
        columns = [
            "",  # 选择框
            "任务ID",  # 隐藏的任务ID列
            "商品ID", 
            "标签", 
            "商品名称", 
            "目标磨损",  # 新增列
            "捡漏价",
            "预期利润率",
            "最小利润率（动态利润率定价有效）",
            "目标售价",
            "扫货定价类型",
            "扫货记录分析",  
            "已买入",  
            "买入限制",
            "状态",
            "操作"
        ]
        self.table.setColumnCount(len(columns))
        self.table.setHorizontalHeaderLabels(columns)
        
        # 隐藏任务ID列
        self.table.setColumnHidden(1, True)
        
        # 设置表格可以水平和垂直滚动
        self.table.setHorizontalScrollMode(QTableWidget.ScrollMode.ScrollPerPixel)
        self.table.setVerticalScrollMode(QTableWidget.ScrollMode.ScrollPerPixel)
        
        # 禁用默认排序
        self.table.setSortingEnabled(False)
        
        # 只允许特定列排序
        header = self.table.horizontalHeader()
        header.sectionClicked.connect(self.on_header_clicked)
        
        # 设置列宽模式
        header.setSectionResizeMode(0, QHeaderView.ResizeMode.Fixed)  # 选择列固定宽度
        self.table.setColumnWidth(0, 50)  # 选择列宽度为50
        
        # 设置其他列为自适应内容宽度
        for i in range(2, len(columns)):
            if i in [3, 10]:  # 商品名称、投资评分列
                header.setSectionResizeMode(i, QHeaderView.ResizeMode.Interactive)
            else:
                header.setSectionResizeMode(i, QHeaderView.ResizeMode.ResizeToContents)
                
        # 设置特定列的最小宽度
        column_widths = {
            0: 50,   # 选择
            2: 80,   # 商品ID
            3: 100,  # 标签
            4: 200,  # 商品名称
            5: 80,   # 目标磨损
            6: 80,   # 捡漏价
            7: 80,   # 预期利润率
            8: 80,   # 最小利润率
            9: 80,   # 目标售价
            10: 100,  # 扫货定价类型
            11: 150,  # 扫货记录分析
            12: 80,  # 已买入
            13: 80,  # 买入限制
            14: 60,  # 状态
            15: 210  # 操作
        }
        
        # 设置列宽
        for col, width in column_widths.items():
            self.table.setColumnWidth(col, width)
        
        # 设置行高自适应
        self.table.verticalHeader().setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents)
        
        # 应用表格样式
        apply_default_table_style(self.table)
        
        # 设置表格样式
        self.table.setStyleSheet("""
            QTableWidget {
                background-color: white;
                alternate-background-color: #fafafa;
                selection-background-color: #e6f7ff;
                selection-color: black;
            }
            QTableWidget::item {
                color: black;
            }
            QHeaderView::section {
                background-color: #f0f0f0;
                color: black;
                padding: 4px;
                border: none;
                border-right: 1px solid #ddd;
                border-bottom: 1px solid #ddd;
            }
        """)
        
        # 启用隔行变色
        self.table.setAlternatingRowColors(True)
        
        # 设置表头样式
        header.setStyleSheet("""
            QHeaderView::section { 
                padding: 0 5px;
            }
        """)
        header.setFixedHeight(40)
        
        # 添加表头复选框
        header_widget = QWidget()
        header_layout = QHBoxLayout(header_widget)
        header_layout.setContentsMargins(0, 0, 0, 0)
        header_layout.setSpacing(0)
        header_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
        # 创建表头复选框
        self.header_checkbox = QCheckBox()
        self.header_checkbox.setStyleSheet("""
            QCheckBox {
                margin: 0;
                padding: 0;
            }
            QCheckBox::indicator {
                width: 16px;
                height: 16px;
            }
            QCheckBox::indicator:unchecked {
                border: 1px solid #d9d9d9;
                background-color: white;
            }
            QCheckBox::indicator:checked {
                border: 1px solid #1890ff;
                background-color: #1890ff;
            }
        """)
        self.header_checkbox.clicked.connect(self.on_header_checkbox_changed)  # 改用clicked信号
        header_layout.addWidget(self.header_checkbox)
        
        # 设置表头第一列的widget
        self.table.setHorizontalHeaderItem(0, QTableWidgetItem(""))
        header_widget.setFixedSize(50, 40)
        header_widget.setParent(header)
        header_widget.move(header.sectionPosition(0), 0)
        header_widget.show()
        
        # 添加到主布局
        layout.addWidget(self.table)

    def init_tags(self):
        """初始化标签选择器"""
        print("开始初始化标签...")
        
        # 清除现有标签
        for i in reversed(range(self.tags_layout.count())): 
            widget = self.tags_layout.itemAt(i).widget()
            if widget:
                widget.setParent(None)
        self.tag_checkboxes.clear()
        
        # 获取所有标签
        all_tags = self.task_manager.get_all_tags()
        print(f"获取到的标签: {all_tags}")
        
        # 创建标签复选框
        for tag in all_tags:
            checkbox = QCheckBox(tag)
            checkbox.setStyleSheet("""
                QCheckBox {
                    padding: 3px 8px;
                    border: 1px solid #d9d9d9;
                    border-radius: 4px;
                    background-color: white;
                    font-size: 13px;
                    min-height: 24px;
                }
                QCheckBox:hover {
                    border-color: #40a9ff;
                }
                QCheckBox:checked {
                    background-color: #e6f7ff;
                    border-color: #1890ff;
                }
                QCheckBox::indicator {
                    width: 16px;
                    height: 16px;
                    margin-right: 4px;
                }
                QCheckBox::indicator:unchecked {
                    border: 1px solid #d9d9d9;
                    background: white;
                }
                QCheckBox::indicator:checked {
                    border: 1px solid #1890ff;
                    background: #1890ff;
                }
            """)
            self.tag_checkboxes[tag] = checkbox
            self.tags_layout.addWidget(checkbox)
            print(f"添加标签: {tag}")
            
        # 添加弹性空间
        self.tags_layout.addStretch()
        print("标签初始化完成")
    
    def on_search(self):
        """点击搜索按钮时触发搜索"""
        keyword = self.search_input.text().strip()
        goods_id = self.id_input.text().strip()
        min_sell_num = self.min_sell_num_input.text().strip()
        min_price = self.min_price_input.text().strip()
        max_price = self.max_price_input.text().strip()
        status = self.status_combo.currentData()
        wear_category = self.wear_combo.currentData()  # 获取选中的外观类型
        
        # 获取选中的标签
        selected_tags = [
            tag for tag, checkbox in self.tag_checkboxes.items()
            if checkbox.isChecked()
        ]
        
        self.load_data(
            keyword=keyword,
            goods_id=goods_id,
            min_sell_num=min_sell_num if min_sell_num else None,
            min_price=min_price if min_price else None,
            max_price=max_price if max_price else None,
            status=status,
            wear_category=wear_category,
            tags=selected_tags
        )
        
    def load_data(self, keyword=None, goods_id=None, min_sell_num=None, min_price=None, max_price=None, status=None, wear_category=None, tags=None):
        """从数据库加载数据"""
        print("开始加载数据...")
        
        # 清空复选框列表
        self.row_checkboxes.clear()
        
        if status == -1:  # 如果选择"全部"，则分别获取启用和停用的任务
            # 获取所有数据，先获取启用的任务，再获取停用的任务
            enabled_tasks = self.task_manager.search_tasks(
                keyword,
                goods_id=goods_id,
                min_sell_num=min_sell_num,
                min_price=min_price,
                max_price=max_price,
                status=1,  # 启用状态
                wear_category=wear_category,
                tags=tags
            )
            
            disabled_tasks = self.task_manager.search_tasks(
                keyword,
                goods_id=goods_id,
                min_sell_num=min_sell_num,
                min_price=min_price,
                max_price=max_price,
                status=0,  # 停用状态
                wear_category=wear_category,
                tags=tags
            )
            
            # 合并任务列表，启用的任务在前面
            tasks = enabled_tasks + disabled_tasks
        else:  # 如果选择了特定状态（启用或停用），则只获取该状态的任务
            tasks = self.task_manager.search_tasks(
                keyword,
                goods_id=goods_id,
                min_sell_num=min_sell_num,
                min_price=min_price,
                max_price=max_price,
                status=status,
                wear_category=wear_category,
                tags=tags
            )
        
        print(f"数据条数: {len(tasks)}")
        
        # 更新表格
        self.table.setRowCount(len(tasks))
        
        print("开始创建表格行...")
        
        for row, task in enumerate(tasks):
            # print(f"\n处理第 {row + 1} 行数据:")
            # 添加复选框
            checkbox = QCheckBox()
            self.row_checkboxes.append(checkbox)  # 保存复选框引用
            
            checkbox.setStyleSheet("""
                QCheckBox {
                    margin: 0;
                    padding: 0;
                }
                QCheckBox::indicator {
                    width: 16px;
                    height: 16px;
                }
                QCheckBox::indicator:unchecked {
                    border: 1px solid #d9d9d9;
                    background-color: white;
                }
                QCheckBox::indicator:checked {
                    border: 1px solid #1890ff;
                    background-color: #1890ff;
                }
            """)
            
            # 连接复选框的点击信号
            checkbox.clicked.connect(self.on_row_checkbox_changed)
            
            # 创建容器并设置布局
            container = QWidget()
            layout = QHBoxLayout(container)
            layout.setContentsMargins(0, 0, 0, 0)
            layout.setSpacing(0)
            layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
            layout.addWidget(checkbox)
            
            self.table.setCellWidget(row, 0, container)
            # print(f"已添加复选框到第 {row + 1} 行")
            
            # 添加任务ID（隐藏列）
            self.table.setItem(row, 1, QTableWidgetItem(str(task['id'])))
            
            # 添加其他列数据
            self.table.setItem(row, 2, QTableWidgetItem(str(task['goods_id'])))
            
            # 标签
            tags = []
            if task['tags']:
                try:
                    if isinstance(task['tags'], str):
                        tags = json.loads(task['tags'])
                    else:
                        tags = task['tags']
                except (json.JSONDecodeError, TypeError):
                    tags = [tag.strip() for tag in task['tags'].split(',') if tag.strip()]
            self.table.setItem(row, 3, QTableWidgetItem(", ".join(tags)))
            
            # 创建商品名称超链接
            name_container = QWidget()
            name_layout = QHBoxLayout(name_container)
            name_layout.setContentsMargins(5, 0, 5, 0)
            name_layout.setSpacing(0)
            
            url = task.get('goods_url', '')
            if url:
                name_label = HyperlinkLabel(task['name'], url)
            else:
                name_label = QLabel(task['name'])
            
            name_layout.addWidget(name_label)
            name_layout.addStretch()
            self.table.setCellWidget(row, 4, name_container)
            
            # 目标磨损
            wear_range = ""
            if task.get('filter_conf'):
                try:
                    # 尝试解析filter_conf字段
                    filter_conf = task.get('filter_conf')
                    if isinstance(filter_conf, str):
                        filter_conf = json.loads(filter_conf)
                    
                    # 获取最小磨损和最大磨损
                    min_wear = filter_conf.get('min_paintwear')
                    max_wear = filter_conf.get('max_paintwear')
                    
                    # 格式化显示
                    if min_wear is not None and max_wear is not None:
                        wear_range = f"{min_wear}-{max_wear}"
                    elif min_wear is not None:
                        wear_range = f"{min_wear}+"
                    elif max_wear is not None:
                        wear_range = f"0-{max_wear}"
                except (json.JSONDecodeError, TypeError, AttributeError) as e:
                    print(f"解析filter_conf失败: {e}")
            
            self.table.setItem(row, 5, QTableWidgetItem(wear_range))
            
            # 捡漏价
            self.table.setItem(row, 6, QTableWidgetItem(f"{task['buy_price_limit']:.2f}" if task.get('buy_price_limit') is not None else '-'))
            
            # 预期利润率
            profit_rate = task.get('profit_rate', 0)
            profit_rate_item = QTableWidgetItem(f"{profit_rate:.2f}%" if profit_rate is not None else '-')
            self.table.setItem(row, 7, profit_rate_item)
            
            # 最小利润率
            min_profit_rate = task.get('min_profit_rate', 0)
            min_profit_rate_item = QTableWidgetItem(f"{min_profit_rate:.2f}%" if min_profit_rate is not None else '-')
            self.table.setItem(row, 8, min_profit_rate_item)
            
            # 目标售价
            self.table.setItem(row, 9, QTableWidgetItem(f"{task['target_sell_price']:.2f}" if task.get('target_sell_price') is not None else '-'))
            
            # 扫货定价类型
            pricing_type = task.get('pricing_type', 0)
            pricing_type_text = {
                0: "固定价格",
                1: "动态利润率",
                2: "固定利润率"
            }.get(pricing_type, "未知")
            pricing_type_item = QTableWidgetItem(pricing_type_text)
            self.table.setItem(row, 10, pricing_type_item)
            
            # 扫货记录分析
            self.update_row_data(row, task)
            
            # 已买入数量（从purchase_count获取）
            bought_item = QTableWidgetItem()
            bought_count = int(task.get('purchase_count', 0))
            bought_item.setData(Qt.ItemDataRole.DisplayRole, bought_count)
            self.table.setItem(row, 12, bought_item)
            
            # 买入限制（设置为数字类型以支持排序）
            buy_num_item = QTableWidgetItem()
            buy_num_item.setData(Qt.ItemDataRole.DisplayRole, int(task['buy_num_limit'] if task['buy_num_limit'] is not None else 0))
            self.table.setItem(row, 13, buy_num_item)
            
            # 状态
            status_item = QTableWidgetItem()
            status_value = task['status']
            status_item.setData(Qt.ItemDataRole.UserRole, status_value)  # 用于排序
            status_item.setText("启用" if status_value == 1 else "停用")  # 显示文本
            self.table.setItem(row, 14, status_item)
            
            # 添加操作按钮
            operation_widget = self.create_operation_buttons(task)
            self.table.setCellWidget(row, 15, operation_widget)
        
        print("\n数据加载完成")
        
        # 重置表头复选框状态
        self.header_checkbox.setChecked(False)

    def init_tags(self):
        """初始化标签选择器"""
        print("开始初始化标签...")
        
        # 清除现有标签
        for i in reversed(range(self.tags_layout.count())): 
            widget = self.tags_layout.itemAt(i).widget()
            if widget:
                widget.setParent(None)
        self.tag_checkboxes.clear()
        
        # 获取所有标签
        all_tags = self.task_manager.get_all_tags()
        print(f"获取到的标签: {all_tags}")
        
        # 创建标签复选框
        for tag in all_tags:
            checkbox = QCheckBox(tag)
            checkbox.setStyleSheet("""
                QCheckBox {
                    padding: 3px 8px;
                    border: 1px solid #d9d9d9;
                    border-radius: 4px;
                    background-color: white;
                    font-size: 13px;
                    min-height: 24px;
                }
                QCheckBox:hover {
                    border-color: #40a9ff;
                }
                QCheckBox:checked {
                    background-color: #e6f7ff;
                    border-color: #1890ff;
                }
                QCheckBox::indicator {
                    width: 16px;
                    height: 16px;
                    margin-right: 4px;
                }
                QCheckBox::indicator:unchecked {
                    border: 1px solid #d9d9d9;
                    background: white;
                }
                QCheckBox::indicator:checked {
                    border: 1px solid #1890ff;
                    background: #1890ff;
                }
            """)
            self.tag_checkboxes[tag] = checkbox
            self.tags_layout.addWidget(checkbox)
            print(f"添加标签: {tag}")
            
        # 添加弹性空间
        self.tags_layout.addStretch()
        print("标签初始化完成")
    
    def on_search(self):
        """点击搜索按钮时触发搜索"""
        keyword = self.search_input.text().strip()
        goods_id = self.id_input.text().strip()
        min_sell_num = self.min_sell_num_input.text().strip()
        min_price = self.min_price_input.text().strip()
        max_price = self.max_price_input.text().strip()
        status = self.status_combo.currentData()
        wear_category = self.wear_combo.currentData()  # 获取选中的外观类型
        
        # 获取选中的标签
        selected_tags = [
            tag for tag, checkbox in self.tag_checkboxes.items()
            if checkbox.isChecked()
        ]
        
        self.load_data(
            keyword=keyword,
            goods_id=goods_id,
            min_sell_num=min_sell_num if min_sell_num else None,
            min_price=min_price if min_price else None,
            max_price=max_price if max_price else None,
            status=status,
            wear_category=wear_category,
            tags=selected_tags
        )
        
    def on_header_checkbox_changed(self):
        """表头复选框状态改变"""
        state = self.header_checkbox.checkState()
        # print(f"\n表头复选框状态改变，当前状态: {state}")
        
        # 只在完全选中或完全未选中时改变行复选框状态
        if state != Qt.CheckState.PartiallyChecked:
            checked = (state == Qt.CheckState.Checked)
            # 阻止行复选框的信号
            for checkbox in self.row_checkboxes:
                checkbox.blockSignals(True)
                checkbox.setChecked(checked)
                checkbox.blockSignals(False)
                # print(f"设置复选框状态: {checked}")
        
        # print("\n表头复选框处理完成")

    def on_row_checkbox_changed(self):
        """行复选框状态改变"""
        # print("\n行复选框状态改变")
        
        # 检查所有复选框的状态
        checked_count = sum(1 for cb in self.row_checkboxes if cb.isChecked())
        total_count = len(self.row_checkboxes)
        
        # print(f"选中数量: {checked_count}, 总数: {total_count}")
        
        # 阻止表头复选框的信号
        self.header_checkbox.blockSignals(True)
        
        # 根据选中情况设置表头复选框状态
        if checked_count == 0:
            # 没有选中任何项
            self.header_checkbox.setCheckState(Qt.CheckState.Unchecked)
            # print("设置表头为未选中状态")
        elif checked_count == total_count:
            # 选中所有项
            self.header_checkbox.setCheckState(Qt.CheckState.Checked)
            # print("设置表头为全选状态")
        else:
            # 部分选中
            self.header_checkbox.setCheckState(Qt.CheckState.PartiallyChecked)
            # print("设置表头为部分选中状态")
        
        self.header_checkbox.blockSignals(False)
        # print("行复选框状态处理完成")

    def get_selected_task_ids(self):
        """获取选中的任务ID列表"""
        # print("\n开始获取选中的任务ID")
        selected_ids = []
        
        # print(f"表格总行数: {self.table.rowCount()}")
        # print(f"复选框列表长度: {len(self.row_checkboxes)}")
        
        # 使用保存的复选框引用
        for row, checkbox in enumerate(self.row_checkboxes):
            # print(f"\n检查第 {row + 1} 行:")
            if checkbox.isChecked():
                # print(f"第 {row + 1} 行被选中")
                try:
                    # 获取任务ID单元格
                    id_item = self.table.item(row, 1)
                    if id_item is None:
                        # print(f"警告：第 {row + 1} 行的任务ID单元格为空")
                        continue
                        
                    # 获取任务ID文本
                    id_text = id_item.text()
                    # print(f"获取到任务ID文本: {id_text}")
                    
                    # 转换为整数
                    task_id = int(id_text)
                    selected_ids.append(task_id)
                    # print(f"成功添加任务ID: {task_id}")
                except Exception as e:
                    print(f"处理第 {row + 1} 行任务ID时出错: {str(e)}")
            # else:
                # print(f"第 {row + 1} 行未选中")
        
        # print(f"\n共找到 {len(selected_ids)} 个选中的任务ID: {selected_ids}")
        return selected_ids

    def on_batch_delete(self):
        """批量删除任务"""
        # print("\n开始批量删除任务...")
        
        # 获取选中的任务ID
        selected_ids = self.get_selected_task_ids()
        # print(f"获取到选中的任务ID列表: {selected_ids}")
        
        if not selected_ids:
            # print("没有选中任何任务，显示提示消息")
            QMessageBox.warning(self, "提示", "请先选择要删除的任务")
            return
            
        # 确认删除
        reply = QMessageBox.question(
            self,
            "确认删除",
            f"确定要删除选中的 {len(selected_ids)} 个任务吗？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            # print("\n用户确认删除，开始执行删除操作")
            error_messages = []
            success_count = 0
            error_count = 0
            
            # 执行删除
            for task_id in selected_ids:
                # print(f"\n开始删除任务 {task_id}")
                try:
                    # print(f"调用TaskManager.delete_task({task_id})")
                    self.task_manager.delete_task(task_id)
                    success_count += 1
                    # print(f"成功删除任务 {task_id}")
                except Exception as e:
                    error_count += 1
                    error_message = f"删除任务出错，任务ID: {task_id}, 错误: {str(e)}"
                    print(error_message)
                    error_messages.append(error_message)
            
            # print(f"\n删除操作完成：成功 {success_count} 个，失败 {error_count} 个")
            
            # 显示结果
            if success_count > 0:
                # print("显示成功消息")
                QMessageBox.information(self, "删除结果", f"成功删除 {success_count} 个任务")
            
            if error_count > 0:
                # print("显示错误消息")
                error_text = "\n".join(error_messages)
                QMessageBox.warning(self, "删除结果", f"删除失败 {error_count} 个任务:\n{error_text}")
            
            # 重新加载数据
            # print("\n重新加载数据")
            self.load_data()
            
            # 取消表头复选框的选中状态
            self.header_checkbox.setChecked(False)

    def on_reset(self):
        """重置搜索条件并重新加载数据"""
        # 清空搜索框
        self.search_input.clear()
        self.id_input.clear()
        self.min_sell_num_input.clear()
        self.min_price_input.clear()
        self.max_price_input.clear()
        self.status_combo.setCurrentIndex(0)  # 重置状态为"全部"
        self.wear_combo.setCurrentIndex(0)    # 重置外观为"全部"
        
        # 取消所有标签选中状态
        for checkbox in self.tag_checkboxes.values():
            checkbox.setChecked(False)
            
        # 重新加载数据
        self.load_data()

    def create_operation_buttons(self, task):
        """创建操作按钮"""
        container = QWidget()
        container.setFixedWidth(210)  # 调整容器宽度（原来是270）
        layout = QHBoxLayout(container)
        layout.setContentsMargins(5, 0, 5, 0)  # 添加左右边距
        layout.setSpacing(8)  # 增加按钮间距
        
        # 编辑按钮
        edit_btn = QPushButton("编辑")
        edit_btn.setFixedSize(55, 25)
        edit_btn.setStyleSheet("""
            QPushButton {
                background-color: #1890ff;
                border: none;
                border-radius: 4px;
                color: white;
                font-size: 12px;
            }
            QPushButton:hover {
                background-color: #40a9ff;
            }
            QPushButton:pressed {
                background-color: #096dd9;
            }
        """)
        edit_btn.clicked.connect(lambda: self.on_edit_task(task))
        layout.addWidget(edit_btn)
        
        # 启用/停用按钮
        toggle_btn = QPushButton("停用" if task['status'] == 1 else "启用")
        toggle_btn.setFixedSize(55, 25)
        toggle_btn.setStyleSheet("""
            QPushButton {
                background-color: """ + ("#ff4d4f" if task['status'] == 1 else "#52c41a") + """;
                border: none;
                border-radius: 4px;
                color: white;
                font-size: 12px;
            }
            QPushButton:hover {
                background-color: """ + ("#ff7875" if task['status'] == 1 else "#73d13d") + """;
            }
            QPushButton:pressed {
                background-color: """ + ("#d9363e" if task['status'] == 1 else "#389e0d") + """;
            }
        """)
        toggle_btn.clicked.connect(lambda: self.on_toggle_status(task))
        layout.addWidget(toggle_btn)
        
        # 删除按钮
        delete_btn = QPushButton("删除")
        delete_btn.setFixedSize(55, 25)
        delete_btn.setStyleSheet("""
            QPushButton {
                background-color: #ff4d4f;
                border: none;
                border-radius: 4px;
                color: white;
                font-size: 12px;
            }
            QPushButton:hover {
                background-color: #ff7875;
            }
            QPushButton:pressed {
                background-color: #d9363e;
            }
        """)
        delete_btn.clicked.connect(lambda: self.on_delete_task(task))
        layout.addWidget(delete_btn)
        
        # 添加弹性空间
        layout.addStretch()
        
        return container

    def on_toggle_status(self, task):
        """切换任务状态"""
        new_status = 0 if task['status'] == 1 else 1
        status_text = "停用" if new_status == 0 else "启用"
        
        reply = QMessageBox.question(
            self,
            "确认操作",
            f"确定要{status_text}该任务吗？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            if self.task_manager.update_task_status(task['id'], new_status):
                self.load_data()  # 重新加载数据
                QMessageBox.information(self, "成功", f"任务已{status_text}")
            else:
                QMessageBox.warning(self, "错误", f"{status_text}任务失败")

    def on_header_clicked(self, logical_index):
        """处理表头点击事件"""
        if logical_index in [6, 7, 8, 13, 14]:  # 捡漏价(6)、预期利润率(7)、最小利润率(8)、买入限制(13)、状态(14)列可排序
            header = self.table.horizontalHeader()
            
            if self.current_sort_column == logical_index:
                # 如果点击的是当前排序列，切换排序顺序
                self.current_sort_order = Qt.SortOrder.DescendingOrder if self.current_sort_order == Qt.SortOrder.AscendingOrder else Qt.SortOrder.AscendingOrder
            else:
                # 如果点击的是新列，默认使用升序
                self.current_sort_column = logical_index
                self.current_sort_order = Qt.SortOrder.AscendingOrder
            
            # 执行排序
            self.table.sortItems(logical_index, self.current_sort_order)
            
            # 显示排序指示器
            header.setSortIndicator(logical_index, self.current_sort_order)
        else:
            # 其他列点击时，清除排序状态
            self.current_sort_column = -1
            self.table.horizontalHeader().setSortIndicator(-1, Qt.SortOrder.AscendingOrder)

    def on_row_double_clicked(self, row, column):
        """处理行双击事件"""
        # 获取该行的复选框
        checkbox_widget = self.table.cellWidget(row, 0)
        if checkbox_widget:
            checkbox = checkbox_widget.layout().itemAt(0).widget()
            # 切换复选框状态
            checkbox.setChecked(not checkbox.isChecked())

    def on_edit_task(self, task):
        """编辑任务"""
        from gui.widgets.edit_task_dialog import EditTaskDialog
        dialog = EditTaskDialog(task, self.task_manager, self)
        if dialog.exec() == EditTaskDialog.DialogCode.Accepted:
            self.load_data()  # 重新加载数据
    
    def on_delete_task(self, task):
        """删除任务"""
        task_id = task['id']
        task_name = task['name']
        
        # 显示确认对话框
        reply = QMessageBox.question(
            self,
            "确认删除",
            f"确定要删除任务 [{task_name}] 吗？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            try:
                # 调用数据库删除
                self.task_manager.delete_task(task_id)
                
                # 重新加载数据
                self.load_data()
                
                QMessageBox.information(self, "成功", "任务删除成功！")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"删除任务失败：{str(e)}")

    def on_import(self):
        """导入任务数据"""
        file_path, _ = QFileDialog.getOpenFileName(
            self,
            "选择任务数据文件",
            "",
            "JSON文件 (*.json)"
        )
        
        if not file_path:
            return
            
        try:
            print(f"\n开始导入任务数据，文件路径: {file_path}")
            
            # 读取JSON文件
            with open(file_path, 'r', encoding='utf-8') as f:
                tasks = json.load(f)
            
            print(f"成功读取JSON文件，任务数量: {len(tasks)}")
            
            if not isinstance(tasks, list):
                QMessageBox.warning(self, "导入失败", "文件格式错误：数据必须是JSON数组")
                return
                
            # 开始导入
            success_count = 0
            update_count = 0
            error_count = 0
            
            for index, task in enumerate(tasks):
                try:
                    # print(f"\n处理第 {index + 1} 个任务:")
                    # print(f"任务数据: {task}")
                    
                    # 检查必填字段
                    required_fields = ['goods_id', 'name']
                    if not all(field in task for field in required_fields):
                        # print(f"缺少必填字段，跳过该任务")
                        error_count += 1
                        continue
                    
                    # 检查商品是否已存在
                    existing_task = self.task_manager.get_task_by_goods_id(task['goods_id'])
                    # print(f"检查商品是否存在: {existing_task is not None}")
                    
                    if existing_task:
                        # 更新现有任务
                        # print(f"更新现有任务，ID: {existing_task['id']}")
                        result = self.task_manager.update_task(existing_task['id'], task)
                        if result:
                            update_count += 1
                            # print("更新成功")
                        else:
                            error_count += 1
                            # print("更新失败")
                    else:
                        # 添加新任务
                        # print("添加新任务")
                        task_id = self.task_manager.add_task(task)
                        if task_id:
                            success_count += 1
                            # print(f"添加成功，新任务ID: {task_id}")
                        else:
                            error_count += 1
                            # print("添加失败")
                        
                except Exception as e:
                    print(f"处理任务失败: {str(e)}")
                    error_count += 1
            
            # print(f"\n导入操作完成：成功 {success_count} 个，更新 {update_count} 个，失败 {error_count} 个")
            
            # 显示导入结果
            message = f"导入完成\n新增: {success_count}\n更新: {update_count}\n失败: {error_count}"
            QMessageBox.information(self, "导入结果", message)
            
            # 刷新数据
            print("\n重新加载数据")
            self.load_data()
            
        except Exception as e:
            print(f"导入文件失败: {str(e)}")
            QMessageBox.critical(self, "导入失败", f"导入文件失败：{str(e)}")

    def on_batch_edit(self):
        """批量编辑任务"""
        # 获取选中的任务ID
        selected_ids = self.get_selected_task_ids()
        
        if not selected_ids:
            QMessageBox.warning(self, "提示", "请先选择要编辑的任务")
            return
            
        # 创建批量编辑对话框
        dialog = TaskBatchEditDialog(selected_ids, self.task_manager, self)
        if dialog.exec() == QDialog.DialogCode.Accepted:
            self.load_data()  # 重新加载数据

    def on_sync_commodity_data(self, task):
        """同步选品数据"""
        # TODO: 实现同步选品数据的逻辑
        print("同步选品数据")

    def get_price_analysis(self, goods_id: int) -> dict:
        """
        获取商品的最新价格分析数据
        
        Args:
            goods_id: 商品ID
            
        Returns:
            dict: 价格分析数据
        """
        try:
            logger.info(f"正在查询商品ID {goods_id} 的价格分析数据")
            analysis_data = self.scan_record_price_analysis_manager.get_latest_analysis(goods_id)
            
            if analysis_data:
                logger.info(f"找到商品ID {goods_id} 的价格分析数据")
                # 格式化异常价格列表
                abnormal_prices = []
                if analysis_data.get('abnormal_prices'):
                    if isinstance(analysis_data['abnormal_prices'], str):
                        abnormal_prices = json.loads(analysis_data['abnormal_prices'])
                    else:
                        abnormal_prices = analysis_data['abnormal_prices']
                    logger.info(f"异常价格列表: {abnormal_prices}")
                
                result = {
                    'analysis_time': analysis_data['analysis_time'],
                    'abnormal_prices': abnormal_prices,
                    'common_sell_price': analysis_data['common_sell_price'],
                    'selling_count': analysis_data.get('selling_count'),
                    'normal_price': analysis_data.get('normal_price')
                }
                logger.info(f"返回的分析数据: {result}")
                return result
            else:
                logger.warning(f"未找到商品ID {goods_id} 的价格分析数据")
                return None
                
        except Exception as e:
            logger.error(f"获取价格分析数据失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return None

    def update_row_data(self, row, task):
        """更新表格行数据"""
        try:
            goods_id = task.get('goods_id')
            if not goods_id:
                logger.warning(f"任务缺少商品ID: {task}")
                return
                
            # 从task中获取价格分析数据
            analysis_data = task.get('price_analysis')
            
            # 先清除原有的单元格内容和widget
            self.table.removeCellWidget(row, 11)
            if self.table.item(row, 11):
                self.table.takeItem(row, 11)
            
            if analysis_data and analysis_data.get('analysis_time'):
                # 格式化分析时间
                analysis_time = analysis_data['analysis_time'].strftime('%y-%m-%d %H:%M:%S')
                
                # 构建分析文本
                lines = []
                lines.append(f"扫货记录分析:{analysis_time}")
                
                # 添加统计数量
                if analysis_data.get('record_count') is not None:
                    lines.append(f"统计数量：{analysis_data['record_count']}条")
                
                # 异常低价
                abnormal_prices_text = ''
                if analysis_data.get('abnormal_prices'):
                    abnormal_prices_list = []
                    for item in analysis_data['abnormal_prices']:
                        price = item['price']
                        count = item['count']
                        profit_rate = item.get('profit_rate', 0)
                        abnormal_prices_list.append(f"{price}元({count}次, {profit_rate:.1f}%)")
                    lines.append(f"异常低价：{', '.join(abnormal_prices_list)}")
                else:
                    lines.append("异常低价：无")
                    
                # 最多售卖价
                if analysis_data.get('top_price_list'):
                    top_prices = json.loads(analysis_data['top_price_list']) if isinstance(analysis_data['top_price_list'], str) else analysis_data['top_price_list']
                    if top_prices:
                        top_prices_list = []
                        for price_info in top_prices:
                            price = price_info.get('price', 0)
                            count = price_info.get('count', 0)
                            top_prices_list.append(f"{price}元({count}次)")
                        lines.append(f"最多售卖价：{', '.join(top_prices_list)}")
                    
                # 历史最低价
                if analysis_data.get('historical_low'):
                    lines.append(f"历史最低价：{analysis_data['historical_low']:.2f}元")
                    
                # 普通售价
                if analysis_data.get('normal_price'):
                    lines.append(f"普通售价：{analysis_data['normal_price']:.2f}元")
                    
                # 常见售价
                if analysis_data.get('common_sell_price'):
                    lines.append(f"常见售价：{analysis_data['common_sell_price']:.2f}元")
                    
                # 在售数量
                if analysis_data.get('selling_count'):
                    lines.append(f"在售数量：{analysis_data['selling_count']}")
                    
                analysis_text = '\n'.join(lines)
                
                # 创建可点击的标签
                label = ClickableLabel(analysis_text)
                label.mousePressEvent = lambda e: self.on_analysis_clicked(row, goods_id)
                self.table.setCellWidget(row, 11, label)
                
            else:
                analysis_text = "等待扫货分析"
                # 设置普通的表格项
                analysis_item = QTableWidgetItem(analysis_text)
                analysis_item.setTextAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft)
                analysis_item.setForeground(QColor(128, 128, 128))
                analysis_item.setToolTip("暂无分析数据")
                self.table.setItem(row, 11, analysis_item)
        except Exception as e:
            logger.error(f"更新表格行数据失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())

    def on_analysis_clicked(self, row, goods_id):
        """处理分析数据点击事件"""
        try:
            dialog = PriceAnalysisHistoryDialog(goods_id, self)
            dialog.exec()
        except Exception as e:
            QMessageBox.warning(self, "错误", f"打开历史数据失败: {str(e)}")

    def on_cell_clicked(self, row, column):
        """处理单元格点击事件"""
        # 如果点击的是捡漏价列（第6列）
        if column == 6:
            # 获取商品ID
            goods_id_item = self.table.item(row, 2)
            if goods_id_item:
                goods_id = int(goods_id_item.text())
                
                # 获取商品名称
                name_widget = self.table.cellWidget(row, 4)
                goods_name = None
                if name_widget:
                    for i in range(name_widget.layout().count()):
                        item = name_widget.layout().itemAt(i).widget()
                        if isinstance(item, QLabel) or isinstance(item, HyperlinkLabel):
                            goods_name = item.text()
                            break
                
                # 打开价格利润率变动记录对话框
                try:
                    dialog = ProfitRatePriceHistoryDialog(goods_id, goods_name, self)
                    dialog.exec()
                except Exception as e:
                    logger.error(f"打开价格利润率变动记录对话框失败: {str(e)}")
                    QMessageBox.warning(self, "错误", f"打开价格利润率变动记录对话框失败: {str(e)}")

    def on_add_task(self):
        """打开添加任务对话框"""
        from .add_task_dialog import AddTaskDialog
        dialog = AddTaskDialog(self)
        if dialog.exec():
            # 如果对话框返回接受状态，刷新任务列表
            self.load_data()

class HyperlinkLabel(QLabel):
    """可点击的超链接标签"""
    def __init__(self, text, url, parent=None):
        super().__init__(parent)
        self.url = url
        self.setText(f'<a href="{url}" style="color: #1890ff; text-decoration: none;">{text}</a>')
        self.setTextFormat(Qt.TextFormat.RichText)
        self.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction)
        self.linkActivated.connect(self.open_url)
        
        # 设置样式
        self.setStyleSheet("""
            QLabel {
                padding: 2px;
            }
            QLabel:hover {
                color: #40a9ff;
            }
        """)
        
    def open_url(self, url):
        """在系统默认浏览器中打开URL"""
        webbrowser.open(url)
